package cn.yunyichina.provider.sb.service.impl;

import cn.yunyichina.provider.framework.data.SpringContextHandler;
import cn.yunyichina.provider.sb.constant.Constant;
import cn.yunyichina.provider.sb.dao.*;
import cn.yunyichina.provider.sb.entity.*;
import cn.yunyichina.provider.sb.util.Util;
import cn.yunyichina.provider.sb.vo.*;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alipay.api.response.AlipayCommerceDataSendResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 15-AK on 2017/9/27.
 */
public class InHospitalReportServiceImpl {

    private static final Logger logger = LoggerFactory.getLogger(InHospitalReportServiceImpl.class);

    private MedicalPatientDao medicalPatientDao = SpringContextHandler.getBean("medicalPatientDao");
    private MedicalCheckingDao medicalCheckingDao = SpringContextHandler.getBean("medicalCheckingDao");
    private MedicalCheckingDetailDao medicalCheckingDetailDao = SpringContextHandler.getBean("medicalCheckingDetailDao");
    private MedicalExaminationDao medicalExaminationDao = SpringContextHandler.getBean("medicalExaminationDao");
    private MedicalOperationRecordDao medicalOperationRecordDao = SpringContextHandler.getBean("medicalOperationRecordDao");
    private MedicalInhospitalReportidsDao medicalInhospitalReportidsDao = SpringContextHandler.getBean("medicalInhospitalReportidsDao");

    private final static String HOSPITAL_CODE = "szszyy";

    public void uploadReportChecking() {
        logger.info("住院检验报告上传开始");
        MedicalPatient queryMedicalPatient = new MedicalPatient();
        queryMedicalPatient.setOrgCode(HOSPITAL_CODE);
        queryMedicalPatient.setBusinessType(new Short("2"));
        queryMedicalPatient.setDownLoadFeeFlag(new Short("1"));
        queryMedicalPatient.setAllCheckingDwnnLoadFlag(new Short("0"));
        List<MedicalPatient> medicalPatientList = medicalPatientDao.select(queryMedicalPatient);
        if (CollectionUtils.isNotEmpty(medicalPatientList)) {
            for (MedicalPatient medicalPatient : medicalPatientList) {
                //先判断检验是否全部下载完成
                if (checkingHasAllOut(medicalPatient)) {
                    //判断是否全部上传完成
                    logger.info("inPatientId={},住院检验报告已全部出来的就诊人信息 medicalPatient={}",new Object[]{medicalPatient.getInpatientId(),JsonUtils.toJsonString(medicalPatient)});
                    executeUploadCheckingMessage(medicalPatient);
                    executeUploadCheckingDetailMessage(medicalPatient);
                    medicalPatient.setAllCheckingDwnnLoadFlag(new Short("1"));
                    medicalPatient.setAllCheckingUpLoadFlag(new Short("1"));
                    medicalPatientDao.update(medicalPatient);
                }
            }
        }
    }

    public void uploadReportOperation() {
        logger.info("住院手术记录上传开始");
        MedicalPatient queryMedicalPatient = new MedicalPatient();
        queryMedicalPatient.setOrgCode(HOSPITAL_CODE);
        queryMedicalPatient.setBusinessType(new Short("2"));
        queryMedicalPatient.setDownLoadFeeFlag(new Short("1"));
        queryMedicalPatient.setAllOperationDownLoadFlag(new Short("0"));
        List<MedicalPatient> medicalPatientList = medicalPatientDao.select(queryMedicalPatient);
        if (CollectionUtils.isNotEmpty(medicalPatientList)) {
            for (MedicalPatient medicalPatient : medicalPatientList) {
                //先判断检验是否全部下载完成
                if (operationHasAllOut(medicalPatient)) {
                    //判断是否全部上传完成
                    logger.info("inPatientId={},住院手术记录已全部出来的就诊人信息 medicalPatient={}",new Object[]{medicalPatient.getInpatientId(),JsonUtils.toJsonString(medicalPatient)});
                    executeUploadSurgeryMessage(medicalPatient);
                    medicalPatient.setAllOperationUpLoadFlag(new Short("1"));
                    medicalPatient.setAllOperationDownLoadFlag(new Short("1"));
                    medicalPatientDao.update(medicalPatient);
                }
            }
        }
    }

    public void uploadReportExamination() {
        logger.info("住院检查信息上传开始");
        MedicalPatient queryMedicalPatient = new MedicalPatient();
        queryMedicalPatient.setOrgCode(HOSPITAL_CODE);
        queryMedicalPatient.setDownLoadFeeFlag(new Short("1"));
        queryMedicalPatient.setBusinessType(new Short("2"));
        queryMedicalPatient.setAllExaminationDownLoadFlag(new Short("0"));
        List<MedicalPatient> medicalPatientList = medicalPatientDao.select(queryMedicalPatient);
        if (CollectionUtils.isNotEmpty(medicalPatientList)) {
            for (MedicalPatient medicalPatient : medicalPatientList) {
                //先判断检验是否全部下载完成
                if (examinationHasAllOut(medicalPatient)) {
                    //判断是否全部上传完成
                    logger.info("inPatientId={},住院检查信息已全部出来的就诊人信息 medicalPatient={}",new Object[]{medicalPatient.getInpatientId(),JsonUtils.toJsonString(medicalPatient)});
                    executeUploadExaminationMessage(medicalPatient);
                    medicalPatient.setAllExaminationDownLoadFlag(new Short("1"));
                    medicalPatient.setAllExaminationUpLoadFlag(new Short("1"));
                    medicalPatientDao.update(medicalPatient);
                }
            }
        }
    }

    public boolean examinationHasAllOut(MedicalPatient medicalPatient) {
        boolean flag = true;
        MedicalInhospitalReportids queryMedicalInhospitalReportids = new MedicalInhospitalReportids();
        queryMedicalInhospitalReportids.setMedicalPatientId(medicalPatient.getId());
        queryMedicalInhospitalReportids.setReportType(new Short("1"));
        List<MedicalInhospitalReportids> medicalInhospitalReportidsList = medicalInhospitalReportidsDao.select(queryMedicalInhospitalReportids);
        //medicalOutpatientFeeDetailList 为空那么该患者没有检查记录直接是返回成功
        if (CollectionUtils.isNotEmpty(medicalInhospitalReportidsList)) {
            //计算门诊费用那边总共有多少个reportId
            Map<String, MedicalInhospitalReportids> totalReportSizeMap = new HashMap<String, MedicalInhospitalReportids>();
            for (MedicalInhospitalReportids mdicalInhospitalReportids : medicalInhospitalReportidsList) {
                totalReportSizeMap.put(mdicalInhospitalReportids.getReportId(), mdicalInhospitalReportids);
            }

            MedicalExamination queryMedicalExamination = new MedicalExamination();
            queryMedicalExamination.setMedicalPatientId(medicalPatient.getId());
            List<MedicalExamination> medicalExaminationList = medicalExaminationDao.select(queryMedicalExamination);
            if (CollectionUtils.isEmpty(medicalExaminationList) || medicalExaminationList.size() != totalReportSizeMap.size()) {
                flag = false;
            } else {
                //如果检查报告出来完了就可以统计rows ,offset了
                int operationoffset = 1;
                for (MedicalExamination medicalExamination : medicalExaminationList) {
                    medicalExamination.setCurrentOffset(operationoffset++);
                    medicalExamination.setTotalRows(medicalExaminationList.size());
                    medicalExaminationDao.update(medicalExamination);
                }
            }
        }else if (medicalPatient.getDownLoadReportIdFlag() == 0){
            flag = false;
        }
        return flag;
    }

    public boolean operationHasAllOut(MedicalPatient medicalPatient) {
        boolean flag = true;
        MedicalInhospitalReportids queryMedicalInhospitalReportids = new MedicalInhospitalReportids();
        queryMedicalInhospitalReportids.setMedicalPatientId(medicalPatient.getId());
        queryMedicalInhospitalReportids.setReportType(new Short("3"));
        List<MedicalInhospitalReportids> medicalInhospitalReportidsList = medicalInhospitalReportidsDao.select(queryMedicalInhospitalReportids);
        //medicalOutpatientFeeDetailList 为空那么该患者没有手术记录直接是返回成功
        if (CollectionUtils.isNotEmpty(medicalInhospitalReportidsList)) {
            //计算门诊费用那边总共有多少个reportId
            Map<String, MedicalInhospitalReportids> totalReportSizeMap = new HashMap<String, MedicalInhospitalReportids>();
            for (MedicalInhospitalReportids medicalInhospitalReportids : medicalInhospitalReportidsList) {
                totalReportSizeMap.put(medicalInhospitalReportids.getReportId(), medicalInhospitalReportids);
            }

            MedicalOperationRecord queryMedicalOperationRecord = new MedicalOperationRecord();
            queryMedicalOperationRecord.setMedicalPatientId(medicalPatient.getId());
            List<MedicalOperationRecord> medicalOperationRecordList = medicalOperationRecordDao.select(queryMedicalOperationRecord);
            if (CollectionUtils.isEmpty(medicalOperationRecordList) || medicalOperationRecordList.size() != totalReportSizeMap.size()) {
                flag = false;
            } else {
                //如果手术报告出来完了就可以统计rows ,offset了
                int operationoffset = 1;
                for (MedicalOperationRecord medicalOperationRecord : medicalOperationRecordList) {
                    medicalOperationRecord.setCurrentOffset(operationoffset++);
                    medicalOperationRecord.setTotalRows(medicalOperationRecordList.size());
                    medicalOperationRecordDao.update(medicalOperationRecord);
                }
            }
        }else if (medicalPatient.getDownLoadReportIdFlag() == 0){
            flag = false;
        }
        return flag;
    }


    public boolean checkingHasAllOut(MedicalPatient medicalPatient) {
        boolean flag = true;
        MedicalInhospitalReportids queryMedicalInhospitalReportids = new MedicalInhospitalReportids();
        queryMedicalInhospitalReportids.setMedicalPatientId(medicalPatient.getId());
        queryMedicalInhospitalReportids.setReportType(new Short("2"));
        List<MedicalInhospitalReportids> medicalInhospitalReportidsList = medicalInhospitalReportidsDao.select(queryMedicalInhospitalReportids);
        if (CollectionUtils.isNotEmpty(medicalInhospitalReportidsList)){
            Map<String,MedicalInhospitalReportids> totalReportSizeMap = new HashMap<>();

            for(MedicalInhospitalReportids medicalInhospitalReportids :medicalInhospitalReportidsList){
                totalReportSizeMap.put(medicalInhospitalReportids.getReportId(),medicalInhospitalReportids);
            }
            MedicalChecking queryMedicalChecking = new MedicalChecking();
            queryMedicalChecking.setMedicalPatientId(medicalPatient.getId());
            List<MedicalChecking> medicalCheckingList = medicalCheckingDao.select(queryMedicalChecking);
            if (CollectionUtils.isEmpty(medicalCheckingList) || medicalCheckingList.size() != totalReportSizeMap.size()) {
                flag = false;
            } else {
                //如果检验报告出来完了就可以统计rows ,offset了
                int checkingoffset = 1;
                for (MedicalChecking medicalChecking : medicalCheckingList) {
                    medicalChecking.setCurrentOffset(checkingoffset++);
                    medicalChecking.setTotalRows(medicalCheckingList.size());
                    medicalCheckingDao.update(medicalChecking);
                }

                MedicalCheckingDetail queryMedicalCheckingDetail = new MedicalCheckingDetail();
                queryMedicalCheckingDetail.setMedicalPatientId(medicalPatient.getId());
                List<MedicalCheckingDetail> medicalCheckingDetailList = medicalCheckingDetailDao.select(queryMedicalCheckingDetail);
                int checkingDetailoffset = 1;
                for (MedicalCheckingDetail medicalCheckingDetail : medicalCheckingDetailList) {
                    medicalCheckingDetail.setCurrentOffset(checkingDetailoffset++);
                    medicalCheckingDetail.setTotalRows(medicalCheckingDetailList.size());
                    medicalCheckingDetailDao.update(medicalCheckingDetail);
                }
            }
        }else if (medicalPatient.getDownLoadReportIdFlag() == 0){
            flag = false;
        }

        return flag;
    }

    public void executeUploadExaminationMessage(MedicalPatient medicalPatient) {
        try {
            logger.info("开始上传住院检查信息");
            MedicalExamination queryMedicalExamination = new MedicalExamination();
            queryMedicalExamination.setMedicalPatientId(medicalPatient.getId());
            List<MedicalExamination> uploadMedicalExaminationList = medicalExaminationDao.select(queryMedicalExamination);
            for (MedicalExamination medicalExamination : uploadMedicalExaminationList) {
                logger.info("inPatientId={},待上传住院检查信息 medicalExamination ={}", new Object[]{medicalExamination.getBusinessFeeId(),JsonUtils.toJsonString(medicalExamination)});
                MedicalInhospitalExaminationVo medicalInhospitalExaminationVo = new MedicalInhospitalExaminationVo();
                String encryptData = Util.encryptMedicalInhospitalExaminationVo(medicalInhospitalExaminationVo.buildMedicalInhospitalExaminationVo(medicalExamination), Constant.ENCRYPT_KEY);
                SbRequest sbRequest = new SbRequest();
                sbRequest.setSceneCode(Constant.MEDICAL_INHOSPITAL_EXAMINATION);
                sbRequest.setEncryptData(encryptData);
                try {
                    AlipayCommerceDataSendResponse response = Util.executeUploadMessage(sbRequest);
                    logger.info("inPatientId={},住院检查信息支付宝响应参数 response={}", new Object[]{medicalExamination.getBusinessFeeId(),JsonUtils.toJsonString(response)});
                    if (response.isSuccess()) {
                        logger.info("inPatientId={},住院检查信息上传成功",medicalExamination.getBusinessFeeId());
                        medicalExamination.setUploadFlag(new Short("1"));
                    } else {
                        logger.info("住院检查信息上传失败");
                        medicalExamination.setExceptionMessage(response.getSubMsg());
                    }
                    medicalExamination.setUploadTimes(medicalExamination.getUploadTimes()+1);
                    medicalExaminationDao.update(medicalExamination);
                } catch (Exception e) {
                    logger.error("住院检查信息上传系统异常", e);
                }
            }
        } catch (Exception e) {
            logger.error("住院检查信息上传系统异常", e);
        }
    }


    public void executeUploadSurgeryMessage(MedicalPatient medicalPatient) {
        try {
            logger.info("开始上传住院手术记录信息");
            MedicalOperationRecord queryMedicalOperationRecord = new MedicalOperationRecord();
            queryMedicalOperationRecord.setMedicalPatientId(medicalPatient.getId());
            List<MedicalOperationRecord> uploadMedicalOperationRecordList = medicalOperationRecordDao.select(queryMedicalOperationRecord);
            for (MedicalOperationRecord medicalOperationRecord : uploadMedicalOperationRecordList) {
                logger.info("inPatientId={},待上传的住院手术记录信息 medicalOperationRecord ={}", new Object[]{medicalOperationRecord.getInpatientId(),JsonUtils.toJsonString(medicalOperationRecord)});
                MedicalInhospitalOperationRecordVo medicalInhospitalOperationRecordVo = new MedicalInhospitalOperationRecordVo();
                String encryptData = Util.encryptMedicalInhospitalOperationRecordVo(medicalInhospitalOperationRecordVo.buildMedicalInhospitalOperationRecordVo(medicalOperationRecord), Constant.ENCRYPT_KEY);
                SbRequest sbRequest = new SbRequest();
                sbRequest.setSceneCode(Constant.MEDICAL_INHOSPITAL_OPERATION_RECORD);
                sbRequest.setEncryptData(encryptData);
                try {
                    AlipayCommerceDataSendResponse response = Util.executeUploadMessage(sbRequest);
                    logger.info("inPatientId={},住院手术记录信息支付宝响应参数 response={}", new Object[]{medicalOperationRecord.getInpatientId(),JsonUtils.toJsonString(response)});
                    if (response.isSuccess()) {
                        logger.info("inPatientId={},住院手术记录信息上传成功",medicalOperationRecord.getInpatientId());
                        medicalOperationRecord.setUploadFlag(new Short("1"));
                    } else {
                        logger.info("住院手术记录信息失败");
                        medicalOperationRecord.setExceptionMessage(response.getSubMsg());
                    }
                    medicalOperationRecord.setUploadTimes(medicalOperationRecord.getUploadTimes()+1);
                    medicalOperationRecordDao.update(medicalOperationRecord);

                } catch (Exception e) {
                    logger.error("住院手术记录信息上传系统异常", e);
                }
            }
        } catch (Exception e) {
            logger.error("住院手术记录信息上传系统异常", e);
        }
    }


    public void executeUploadCheckingMessage(MedicalPatient medicalPatient) {
        try {
            logger.info("开始上传住院检验列表信息");
            MedicalChecking queryMedicalChecking = new MedicalChecking();
            queryMedicalChecking.setMedicalPatientId(medicalPatient.getId());
            List<MedicalChecking> uploadCheckingList = medicalCheckingDao.select(queryMedicalChecking);
            if (CollectionUtils.isNotEmpty(uploadCheckingList)){
                for (MedicalChecking medicalChecking :uploadCheckingList){
                    logger.info("inPatientId={},待上传住院检验列表信息 medicalChecking ={}", new Object[]{medicalChecking.getBusinessFeeId(),JsonUtils.toJsonString(medicalChecking)});
                    MedicalInhospitalCheckingVo medicalOutpatientFeeVo = new MedicalInhospitalCheckingVo();
                    String encryptData = Util.encryptMedicalInhospitalCheckingVo(medicalOutpatientFeeVo.buildMedicalInhospitalCheckingVo(medicalChecking), Constant.ENCRYPT_KEY);
                    SbRequest sbRequest = new SbRequest();
                    sbRequest.setSceneCode(Constant.MEDICAL_INHOSPITAL_CHECKING);
                    sbRequest.setEncryptData(encryptData);
                    try {
                        AlipayCommerceDataSendResponse response = Util.executeUploadMessage(sbRequest);
                        logger.info("inPatientId={},住院检验列表信息支付宝响应参数 response={}", new Object[]{medicalChecking.getBusinessFeeId(),JsonUtils.toJsonString(response)});
                        if (response.isSuccess()) {
                            logger.info("住院检验列表信息上传成功");
                            medicalChecking.setUploadFlag(new Short("1"));
                            medicalChecking.setUploadTimes(medicalChecking.getUploadTimes()+1);
                        } else {
                            logger.info("inPatientId={},住院检验列表信息上传失败",medicalChecking.getBusinessFeeId());
                            medicalChecking.setUploadTimes(medicalChecking.getUploadTimes()+1);
                            medicalChecking.setExceptionMessage(response.getSubMsg());
                        }
                        medicalCheckingDao.update(medicalChecking);
                    } catch (Exception e) {
                        logger.error("住院检验列表信息上传系统异常", e);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("住院检验列表信息上传系统异常", e);
        }
    }


    public void executeUploadCheckingDetailMessage(MedicalPatient medicalPatient) {
        try {
            logger.info("开始上传住院检验明细信息");
            MedicalCheckingDetail queryMedicalCheckingDetail = new MedicalCheckingDetail();
            queryMedicalCheckingDetail.setMedicalPatientId(medicalPatient.getId());
            List<MedicalCheckingDetail> uploadCheckingDetailList = medicalCheckingDetailDao.select(queryMedicalCheckingDetail);

            for (MedicalCheckingDetail medicalCheckingDetail : uploadCheckingDetailList) {
                logger.info("inPatientId={},待上传住院检验明细信息medicalCheckingDetail ={}", new Object[]{medicalCheckingDetail.getBusinessFeeId(),JsonUtils.toJsonString(medicalCheckingDetail)});
                MedicalInhospitalCheckingDetailVo medicalInhospitalCheckingDetailVo = new MedicalInhospitalCheckingDetailVo();
                String encryptData = Util.encryptMedicalInhospitalCheckingDetailVo(medicalInhospitalCheckingDetailVo.buildMedicalInhospitalCheckingDetailVo(medicalCheckingDetail), Constant.ENCRYPT_KEY);
                SbRequest sbRequest = new SbRequest();
                sbRequest.setSceneCode(Constant.MEDICAL_INHOSPITAL_CHECKING_DETAIL);
                sbRequest.setEncryptData(encryptData);
                try {
                    AlipayCommerceDataSendResponse response = Util.executeUploadMessage(sbRequest);
                    logger.info("inPatientId={},住院检验明细信息支付宝响应参数 response={}", new Object[]{medicalCheckingDetail.getBusinessFeeId(),JsonUtils.toJsonString(response)});
                    if (response.isSuccess()) {
                        logger.info("inPatientId={},住院检验明细信息上传成功",medicalCheckingDetail.getBusinessFeeId());
                        medicalCheckingDetail.setUploadFlag(new Short("1"));
                    } else {
                        logger.info("住院检验明细信息上传失败");
                        medicalCheckingDetail.setExceptionMessage(response.getSubMsg());
                    }
                    medicalCheckingDetail.setUploadTimes(medicalCheckingDetail.getUploadTimes()+1);
                    medicalCheckingDetailDao.update(medicalCheckingDetail);

                } catch (Exception e) {
                    logger.error("住院检验明细信息上传系统异常", e);
                }
            }
        } catch (Exception e) {
            logger.error("住院检验明细信息上传系统异常", e);
        }
    }

}
